<?php
namespace Home\Controller;
use Think\Controller;
class CheckController extends CommonController
{
    public function auto_check(){
        $user_db = M('user','',C('DB2'));
        $user_examine_db = M('user_examine','',C('DB2'));

//        $data = $user_db->alias('a')->join('user_login b on a.mobile=b.mobile')->where(array('a.user_msg_verify'=>'1','a.work_verify'=>'1','a.mobile_verify'=>'3','a.urgent_verify'=>'1','a.cert_status'=>'4','b.mobilefirm'=>array('like','iPhone%')))->field('a.id,a.user_msg_verify as usermsg_verify,a.taobao_verify,a.mobile_verify,a.urgent_verify as contact_verify,a.work_verify,a.cert_status,b.mobilefirm,a.username as truename,a.identity_num as id_card,a.mobile,b.lng_lat,b.register_ip')->limit(5)->select();
        $data1 = $user_db->alias('a')->join('user_login b on a.mobile=b.mobile')->join('workflow c on c.shop_identifier=a.shop_identifier')->where(array('a.user_msg_verify'=>'1','a.work_verify'=>'1','a.mobile_verify'=>'3','a.urgent_verify'=>'1','a.cert_status'=>'4','a.taobao_verify'=>'3','c.taobao'=>'1'))->field('a.id,a.user_msg_verify as usermsg_verify,a.taobao_verify,a.mobile_verify,a.urgent_verify as contact_verify,a.work_verify,a.cert_status,b.mobilefirm,a.username as truename,a.identity_num as id_card,a.mobile,b.lng_lat,b.register_ip')->limit(5)->select();
        $data2 = $user_db->alias('a')->join('user_login b on a.mobile=b.mobile')->join('workflow c on c.shop_identifier=a.shop_identifier')->where(array('a.user_msg_verify'=>'1','a.work_verify'=>'1','a.mobile_verify'=>'3','a.urgent_verify'=>'1','a.cert_status'=>'4','c.taobao'=>'2'))->field('a.id,a.user_msg_verify as usermsg_verify,a.taobao_verify,a.mobile_verify,a.urgent_verify as contact_verify,a.work_verify,a.cert_status,b.mobilefirm,a.username as truename,a.identity_num as id_card,a.mobile,b.lng_lat,b.register_ip')->limit(5)->select();
//        var_dump($data);
//        var_dump($data2);
//        die;

        $list = array_merge($data1,$data2);
//        $list = $data1;
//        var_dump($list);die;
        if(empty($list)){
            exit();
        }
        foreach ($list as $k=>$v){
            var_dump($v['id']);
            $is_has_check = M('user_examine','',C('DB2'))->where(Array('type'=>'1','user_id'=>$v['id']))->getField('id');
//            var_dump($is_has_check);die;
            if($v['usermsg_verify']==1&&$v['contact_verify']==1&&$v['mobile_verify']==3&&$v['work_verify']=='1'&&empty($is_has_check)) {
//                if (strpos($v['mobilefirm'], 'iP') === false && $v['taobao_verify'] == '3') {
                    $data2 = array('K0001', 'K0002', 'K0005', 'K0007', 'K0009', 'K0011', 'K0012', 'K0014', 'K0017', 'K0019', 'K0020','K0023', 'K0025', 'K0028', 'K0029', 'K0030', 'K0031', 'K0032', 'K0033', 'K0034', 'K0035', 'K0036', 'Z0008','K0037','K0038','D0001','K0039');
                    $data1 = array('C001', 'C002', 'C003', 'C004', 'C005', 'C006', 'C007', 'J008', 'J009', 'J010', 'J011', 'J012', 'J013', 'J014', 'J015', 'J016', 'J017', 'J018', 'J0021');
                    $user_db->where(array('id' => $v['id']))->save(array('checkstatus' => '2', 'statustype' => '1'));
                    foreach ($data2 as $key => $value) {
                        $add = array(
                            'user_id' => $v['id'],
                            'type' => '1',
                            'status' => '0',
                            'number' => $data2[$key],
                        );
                        $addnum[] = $add;
                    }
                    $user_examine_db->addALL($addnum);
                    $addnum = '';
                    foreach ($data1 as $key1 => $value) {
                        $add1 = array(
                            'user_id' => $v['id'],
                            'type' => '2',
                            'status' => '0',
                            'number' => $data1[$key1],
                        );
                        $addnum1[] = $add1;
                    }
                    $user_examine_db->addALL($addnum1);
                    $addnum1 = '';
                    $user_db->where(array('id'=>$v['id']))->setField('cert_status','6');
                    $this->cl_sms_check($v['mobile']);
                    $add_msg = array(
                        'user_id'=>'5',
                        'user_name'=>'系统消息',
                        'receive_id'=>$v['id'],
                        'message'=>'尊敬的用户，您的资料已经进入审核，可以联系客服咨询',
                        'send_time'=>time(),
                        'type'=>'1',
                    );
                     M('chat_record_copy','',C('DB2'))->add($add_msg);
                    continue;
            }
            $user_db->where(array('id'=>$v['id']))->setField('cert_status','6');
        }
    }
    public function zzc_jm(){
        $user_id = I('user_id');
        if(empty($user_id)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $data = M('user','',C('DB2'))->alias('a')->join('user_login b on a.mobile=b.mobile')->where(array('a.id'=>$user_id))->field('a.username as truename,a.identity_num as id_card,a.mobile,b.register_ip,b.lng_lat,a.shop_identifier')->find();
        if(empty($data)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        if(strpos($data['lng_lat'],'lat')!==false){
            $coordinate = explode(',', $data['lng_lat']);
            $lat = explode(':', $coordinate[0])[1];
            $lon = explode(':', $coordinate[1])[1];
        }else{
            $lat = explode(',', $data['lng_lat'])[1];
            $lon = explode(',', $data['lng_lat'])[0];
        }
       $res = $this->zzc_search($data['truename'],$data['id_card'],$data['mobile'],$data['register_ip'],$lon,$lat);
        if(!empty($res['errorCode'])){
            echo json_encode(array('ret'=>'1002','code'=>'error'));
            exit();
        }else{
            echo json_encode(array('ret'=>'1001','code'=>'success'));
            exit();
        }
    }

    public function qh_jm(){
        $user_id = I('user_id');
//        $user_id = '1158';
        if(empty($user_id)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $mobile = M('user','',C('DB2'))->where(['id'=>$user_id])->field('id,mobile,shop_identifier')->find();
        if(empty($mobile['id'])){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $this->test($mobile['id']);
        $has_qh_user_loan_platform = M('qh_user_loan_platform','',C('DB2_ZX'))->where(['mobile'=>$mobile['mobile']])->getField('id');
//        var_dump($has_qh_user_loan_platform);
        $has_qh_user_risk_hint = M('qh_user_risk_hint','',C('DB2_ZX'))->where(['mobile'=>$mobile['mobile']])->getField('id');
//        var_dump($has_qh_user_risk_hint);/
        if(empty($has_qh_user_loan_platform)||empty($has_qh_user_risk_hint)){
            echo json_encode(array('ret'=>'1002','code'=>'error'));
            exit();
        }
            echo json_encode(array('ret'=>'1001','code'=>'success'));
            exit();
    }
    public function get_qh(){
        $user_id = I('user_id');
        if(empty($user_id)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $mobile = M('user','',C('DB2'))->where(['id'=>$user_id])->getField('id');
        $mobile1 = M('user','',C('DB2'))->where(['id'=>$user_id])->getField('mobile');
        $has_qh_user_loan_platform = M('qh_user_loan_platform','',C('DB2_ZX'))->where(['mobile'=>$mobile1])->getField('id');
        $has_qh_user_risk_hint = M('qh_user_risk_hint','',C('DB2_ZX'))->where(['mobile'=>$mobile1])->getField('id');
        if(empty($has_qh_user_loan_platform)||empty($has_qh_user_risk_hint)){
            $this->test($mobile);
            echo json_encode(array('ret'=>'1001','code'=>'success'));
            exit();
        }
        $qh_data = M('qh_user_loan_platform','',C('DB2_ZX'))->where(['mobile'=>$mobile1,'ctime'=>['gt',time()-60*60*24*15]])->getField('id');
        $qh_data1 = M('qh_user_risk_hint','',C('DB2_ZX'))->where(['mobile'=>$mobile1,'ctime'=>['gt',time()-60*60*24*15]])->getField('id');
        if(empty($qh_data)||empty($qh_data1)){
            $this->test($mobile);
            echo json_encode(array('ret'=>'1001','code'=>'success'));
            exit();
        }
        echo json_encode(array('ret'=>'1002','code'=>'该用户无需更新数据'));
        exit();
    }
    //前海钟志成数据更新
    public function get_new_data(){
        $user_id = I('user_id');
        if(empty($user_id)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $data = M('user','',C('DB2'))->alias('a')->join('user_login b on a.mobile=b.mobile')->where(array('a.id'=>$user_id))->field('a.id,a.username as truename,a.identity_num as id_card,a.mobile,b.register_ip,b.lng_lat,a.shop_identifier')->find();
        if(empty($data)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        if(empty($data['truename'])||empty($data['id_card'])||empty($data['mobile'])||empty($data['register_ip'])||empty($data['lng_lat'])){
            echo json_encode(array('ret'=>'1002','code'=>'该用户数据不完整'));
            exit();
        }
        if(strpos($data['lng_lat'],'lat')!==false){
            $coordinate = explode(',', $data['lng_lat']);
            $lat = explode(':', $coordinate[0])[1];
            $lon = explode(':', $coordinate[1])[1];
        }else{
            $lat = explode(',', $data['lng_lat'])[1];
            $lon = explode(',', $data['lng_lat'])[0];
        }
        $res = $this->zzc_search($data['truename'],$data['id_card'],$data['mobile'],$data['register_ip'],$lon,$lat);
        if(!empty($res['errorCode'])){
            echo json_encode(array('ret'=>'1002','code'=>'error'));
            exit();
        }
        $this->test($user_id);
        $has_qh_user_loan_platform = M('qh_user_loan_platform','',C('DB2_ZX'))->where(['user_id'=>$user_id])->getField('id');
        $has_qh_user_risk_hint = M('qh_user_risk_hint','',C('DB2_ZX'))->where(['user_id'=>$user_id])->getField('id');
        if(empty($has_qh_user_loan_platform)||empty($has_qh_user_risk_hint)){
            echo json_encode(array('ret'=>'1002','code'=>'获取数据失败'));
            exit();
        }
        $url = "http://dnqxfv2.hzdouniu.cn/haoxin/deducted";
        $ChargingAdd= array(
            'shopIdentifier'=>$data['shop_identifier'],
            'mobile'=>$data['mobile'],
            'money'=>5,
            'detail'=>'商户更新征信数据',
            'type'=>'1',
            'costType'=>'2',
        );

        $result = $this->curl_post_https($url,$ChargingAdd);
        json_decode($result,true);
        echo json_encode(array('ret'=>'1001','code'=>'成功'));
        exit();
    }
    function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式

    }
    public function ty_jm(){
        $user_id = I('user_id');
        if(empty($user_id)){
            echo json_encode(array('ret'=>'1002','code'=>'该user_id无效'));
            exit();
        }
        $data = M('user','',C('DB2'))->where(array('id'=>$user_id))->field('id,username as truename,identity_num as id_card,mobile')->find();
        $params = array(
            # 基本字段
            'idNumber' => $data['id_card'],
            'phoneNumber' => '0086-' . $data['mobile'],
            # 可选字段
            'name' => $data['truename']
        );
        $zyres1 = $this->antiFraud($params);
//         var_dump($zyres1);die;
        $zy['user_id'] = $data['id'];
        $zy['code'] = $zyres1['code'];
        $zy['codeDesc'] = $zyres1['codeDesc'];
        $zy['found'] = $zyres1['found'];
        $zy['idFound'] = $zyres1['idFound'];
        $zy['message'] = $zyres1['message'];
        $zy['riskScore'] = $zyres1['riskScore'];
        M('ty_risk', '', C('DB2_ZX'))->add($zy);
        if (!empty($zyres1['riskInfo'])) {
            foreach ($zyres1['riskInfo'] as $key => $value) {
                $zy1['user_id'] = $data['id'];
                $zy1['riskCode'] = $value['riskCode'];
                $zy1['riskCodeValue'] = $value['riskCodeValue'];
                $data_s2[] = $zy1;
            }
        }
        $res=M('ty_risk_detail', '', C('DB2_ZX'))->addAll($data_s2);
        if($res){
            echo json_encode(array('ret'=>'1001','code'=>'success'));
            exit();
        }else{
            echo json_encode(array('ret'=>'1002','code'=>'error'));
            exit();
        }
    }
    static function cl_sms($mobile, $content)
    {
        date_default_timezone_set('PRC');//设置时区
        $url = 'https://smssh1.253.com/msg/send/json';
        $data['account'] = 'N3075640';
        $data['password'] = 'C8gWliKHwneaf5';
        $data['msg'] = '【趣消费】' . $content;
        $data['phone'] = $mobile;
        $data['sendtime'] = date('YmdHi');
        $data['report'] = 'true';
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::set_curl($url, json_encode($data), $header);
        $res = json_decode($result, true);
        if ($res['code'] == '0') {
            return true;
        } else {
            return $res['errorMsg'];
        }
    }
    public function set_curl($url, $data = array(), $header = '')
    {
        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }

    /**
     * 创蓝短信检测（判断号码是否为空号或者其他）
     * @param string $mobile 手机号
     * @param string $content 内容
     */
    #这个是创蓝的检测号码状态的接口，但他这个一般是一到两个月更新一次的
    public function cl_sms_check($mobile)
    {
        header("Content-type: text/html; charset=utf-8");
        $first=M('cl_mobile_status_detail','',C('DB2_ZX'))->where(['mobile'=>$mobile])->order('id desc')->field('result_code,mobile,status,ctime')->find();
//        var_dump($first);die;
        //如果first为空或者获取时间不是当日，那么就允许再次获取
        if(empty($first)||strtotime(date('Y-m-d',$first['ctime']))!=strtotime(date('Y-m-d',time()))){
            date_default_timezone_set('PRC');//设置时区
            $url = 'https://kh_bd.253.com//feign/apiMobileTest/findByMobile';
            $data['apiName'] = 'S9992859';//道森坦利账号
            $data['password'] = 'pwd1524430';//道森坦利密码
            $data['mobile'] = $mobile;
            //        $header = array('Content-Type:application/json;charset=utf-8');
            $result = self::getcurl($url, $data);
            $result=json_decode($result,true);
            //		mobile_status
            $this->cl_add_data($result,$mobile,$first['status']);
        }
        return $result;
    }
    public function cl_add_data($data,$mobile,$before_status){
        if(!empty($data)){
            $res=['result_msg'=>$data['resultMsg'],
                'result_code'=>$data['resultCode'],
                'mobile'=>$data['resultObj']['mobile'],
                'last_time'=>substr($data['resultObj']['lastTime'],0,10),
                'area'=>$data['resultObj']['area'],
                'number_type'=>$data['resultObj']['numberType'],
                'charges_status'=>$data['resultObj']['chargesStatus'],
                'status'=>$data['resultObj']['status'],
                'before_status'=>$before_status,
                'ctime'=>time()
            ];
            M('cl_mobile_status_detail','',C('DB2_ZX'))->add($res);
            M('api_log','',C('DB2_ZX'))->add(['api'=>'创蓝空号检测','mobile'=>$mobile,'content'=>'调用结果:'.$data['resultMsg'],'ctime'=>time()]);
        }else{
            M('api_log','',C('DB2_ZX'))->add(['api'=>'创蓝空号检测','mobile'=>$mobile,'content'=>'调用结果:返回信息为空','ctime'=>time()]);
        }
    }

    /**
     * 中智城查询并且存表接口
     * 2018-04-24
     * @param string $name 用户名
     * @param string $pid 用户身份证号
     * @param string $mobile 用户手机号
     * @param string $ip 用户注册时候所在ip地址
     * @param string $lng 用户注册时候的经度
     * @param string $lat 用户注册时候的纬度
     */
    public function zzc_search($name='',$pid='',$mobile='',$ip='',$lng='',$lat=''){
        $zzc_name='705188245@qq.com';//中智城账号
        $zzc_pwd='Jyyjr@0577';//中智城账号密码
//        $url='https://test2.intellicredit.cn/riskcontrol/api/v1/applicant/risk?source=morpho';//测试
        $url='https://riskcontrol3.intellicredit.cn/api/v1/applicant/risk?source=morpho';//正式
        $header=array("Authorization:Basic ".base64_encode($zzc_name.':'.$zzc_pwd) ,'Content-Type:application/json');
        $data['name']=$name;//用户名
        $data['pid']=$pid;//用户身份号
        $data['mobile']=$mobile;//用户手机号
        $data['loan_type']='1';//借贷类型，默认1，现金贷
        $data['device']=[
            'ip_address'=>$ip,//用户当前ip
            'gps_longitude'=>$lng,//用户当前经度
            'gps_latitude'=>$lat//用户当前纬度
        ];
        $res=self::getcurl($url,json_encode($data),$header);
//        var_dump($res);
        $res=json_decode($res,true);
        if(!empty($res['errorCode'])){
            M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$data['mobile'],'content'=>$res['errorMessage'],'ctime'=>time()]);
        }else{
            $this->zzc_result_handle($res,$data['mobile']);
        }
        return $res;
    }
    public function zzc_search_gcs($name='',$pid='',$mobile='',$ip='',$lng='',$lat=''){
        $zzc_name='705188245@qq.com';//中智城账号
        $zzc_pwd='Jyyjr@0577';//中智城账号密码
//        $url='https://test2.intellicredit.cn/riskcontrol/api/v1/applicant/risk?source=morpho';//测试
        $url='https://riskcontrol.intellicredit.cn/api/v1/applicant/risk?source=morpho';//正式
        $header=array("Authorization:Basic ".base64_encode($zzc_name.':'.$zzc_pwd) ,'Content-Type:application/json');
        $data['name']=$name;//用户名
        $data['pid']=$pid;//用户身份号
        $data['mobile']=$mobile;//用户手机号
        $data['loan_type']='1';//借贷类型，默认1，现金贷
        $data['device']=[
            'ip_address'=>$ip,//用户当前ip
            'gps_longitude'=>$lng,//用户当前经度
            'gps_latitude'=>$lat//用户当前纬度
        ];
        $res=self::getcurl($url,json_encode($data),$header);
//        var_dump($res);
        $res=json_decode($res,true);
//        var_dump($res);
        if(!empty($res['errorCode'])){
            M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$data['mobile'],'content'=>$res['errorMessage'],'ctime'=>time()]);
        }else{
            $this->zzc_result_handle($res,$data['mobile']);
        }
        return $res;
    }

    /**
     * 对中智城查询的结果进行处理
     * @param array $res 查询返回结果
     * @param int $mobile 用户手机号
     */
    public function zzc_result_handle($res,$mobile){
        $zzc_velocitycheck_pid_db=M('zzc_velocitycheck_pid','','DB2_ZX');
        $zzc_velocitycheck_mobile_db=M('zzc_velocitycheck_mobile','','DB2_ZX');
        $zzc_loaninfo_pid_db=M('zzc_loaninfo_pid','','DB2_ZX');
        $zzc_loaninfo_mobile_db=M('zzc_loaninfo_mobile','','DB2_ZX');
        $zzc_blacklist_pid_db=M('zzc_blacklist_pid','','DB2_ZX');
        $zzc_blacklist_mobile_db=M('zzc_blacklist_mobile','','DB2_ZX');
        $time=time();
        //中智城--流程查询--身份证维度表
        $data_pid['mobile_count_d30']=$res['velocityCheck']['0']['pid']['timeScopes']['0']['mobileCount'];
        $data_pid['cross_tenant_apps_number_d30']=$res['velocityCheck']['0']['pid']['timeScopes']['0']['crossTenantAppsNumber'];
        $data_pid['mobile_count_d60']=$res['velocityCheck']['0']['pid']['timeScopes']['1']['mobileCount'];
        $data_pid['cross_tenant_apps_number_d60']=$res['velocityCheck']['0']['pid']['timeScopes']['1']['crossTenantAppsNumber'];
        $data_pid['mobile_count_d90']=$res['velocityCheck']['0']['pid']['timeScopes']['2']['mobileCount'];
        $data_pid['cross_tenant_apps_number_d90']=$res['velocityCheck']['0']['pid']['timeScopes']['2']['crossTenantAppsNumber'];
        $data_pid['mobile_count_d180']=$res['velocityCheck']['0']['pid']['timeScopes']['3']['mobileCount'];
        $data_pid['cross_tenant_apps_number_d180']=$res['velocityCheck']['0']['pid']['timeScopes']['3']['crossTenantAppsNumber'];
        $data_pid['ctime']=$time;
        $data_pid['mobile']=$mobile;
        $res1=$zzc_velocitycheck_pid_db->add($data_pid);
        $res1===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_velocitycheck_pid表插入失败','ctime'=>time()]):true;

        //中智城--流程查询--手机维度表
        $data_mobile['mobile_count_d30']=$res['velocityCheck']['0']['mobile']['timeScopes']['0']['mobileCount'];
        $data_mobile['cross_tenant_apps_number_d30']=$res['velocityCheck']['0']['mobile']['timeScopes']['0']['crossTenantAppsNumber'];
        $data_mobile['mobile_count_d60']=$res['velocityCheck']['0']['mobile']['timeScopes']['1']['mobileCount'];
        $data_mobile['cross_tenant_apps_number_d60']=$res['velocityCheck']['0']['mobile']['timeScopes']['1']['crossTenantAppsNumber'];
        $data_mobile['mobile_count_d90']=$res['velocityCheck']['0']['mobile']['timeScopes']['2']['mobileCount'];
        $data_mobile['cross_tenant_apps_number_d90']=$res['velocityCheck']['0']['mobile']['timeScopes']['2']['crossTenantAppsNumber'];
        $data_mobile['mobile_count_d180']=$res['velocityCheck']['0']['mobile']['timeScopes']['3']['mobileCount'];
        $data_mobile['cross_tenant_apps_number_d180']=$res['velocityCheck']['0']['mobile']['timeScopes']['3']['crossTenantAppsNumber'];
        $data_mobile['ctime']=$time;
        $data_mobile['mobile']=$mobile;
        $res2=$zzc_velocitycheck_mobile_db->add($data_mobile);
        $res2===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_velocitycheck_mobile表插入失败','ctime'=>time()]):true;

        //中智城--黑名单查询--身份证维度
        $data_blacklist_pid['last_confirm_status']=$res['blacklist']['pid']['lastConfirmStatus'];
        $data_blacklist_pid['black_level']=$res['blacklist']['pid']['blackLevel'];
        $data_blacklist_pid['last_6m_tenant_count']=$res['blacklist']['pid']['last6MTenantCount'];
        $data_blacklist_pid['last_6m_query_count']=$res['blacklist']['pid']['last6MQueryCount'];
        $data_blacklist_pid['last_confirm_at_days']=$res['blacklist']['pid']['lastConfirmAtDays'];
        $data_blacklist_pid['last_12m_max_confirm_status']=$res['blacklist']['pid']['last12MMaxConfirmStatus'];
        $data_blacklist_pid['ctime']=$time;
        $data_blacklist_pid['mobile']=$mobile;
        $res3=$zzc_blacklist_pid_db->add($data_blacklist_pid);
        $res3===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_blacklist_pid表插入失败','ctime'=>time()]):true;

        //中智城--黑名单查询--手机维度
        $data_blacklist_mobile['last_confirm_status']=$res['blacklist']['mobile']['lastConfirmStatus'];
        $data_blacklist_mobile['black_level']=$res['blacklist']['mobile']['blackLevel'];
        $data_blacklist_mobile['last_6m_tenant_count']=$res['blacklist']['mobile']['last6MTenantCount'];
        $data_blacklist_mobile['last_6m_query_count']=$res['blacklist']['mobile']['last6MQueryCount'];
        $data_blacklist_mobile['last_confirm_at_days']=$res['blacklist']['mobile']['lastConfirmAtDays'];
        $data_blacklist_mobile['last_12m_max_confirm_status']=$res['blacklist']['mobile']['last12MMaxConfirmStatus'];
        $data_blacklist_mobile['ctime']=$time;
        $data_blacklist_mobile['mobile']=$mobile;
        $res4=$zzc_blacklist_mobile_db->add($data_blacklist_mobile);
        $res4===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_blacklist_mobile表插入失败','ctime'=>time()]):true;

        //中智城--批核&贷后共享数据 --身份证号维度
        $data_loaninfo_pid['max_loan_period_days_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['maxLoanPeriodDays'];
        $data_loaninfo_pid['average_loan_amount_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['averageLoanAmount'];
        $data_loaninfo_pid['overdue_for2_term_tenant_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['overdueFor2TermTenantCount'];
        $data_loaninfo_pid['max_loan_amount_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['maxLoanAmount'];
        $data_loaninfo_pid['average_tenant_gap_days_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['averageTenantGapDays'];
        $data_loaninfo_pid['months_from_last_overdue_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['monthsFromLastOverdue'];
        $data_loaninfo_pid['loan_tenant_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['loanTenantCount'];
        $data_loaninfo_pid['query_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['queryCount'];
        $data_loaninfo_pid['overdue_loan_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['overdueLoanCount'];
        $data_loaninfo_pid['loan_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['loanCount'];
        $data_loaninfo_pid['remaining_amount_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['remainingAmount'];
        $data_loaninfo_pid['max_overdue_days_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['maxOverdueDays'];
        $data_loaninfo_pid['months_from_first_loan_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['monthsFromFirstLoan'];
        $data_loaninfo_pid['overdue_tenant_count_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['overdueTenantCount'];
        $data_loaninfo_pid['months_for_normal_repay_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['monthsForNormalRepay'];
        $data_loaninfo_pid['days_from_last_loan_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['daysFromLastLoan'];
        $data_loaninfo_pid['average_loan_gap_days_d360']=$res['loanInfo']['pid']['timeScopes']['D360']['averageLoanGapDays'];
        $data_loaninfo_pid['max_loan_period_days_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['maxLoanPeriodDays'];
        $data_loaninfo_pid['average_loan_amount_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['averageLoanAmount'];
        $data_loaninfo_pid['loan_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['loanCount'];
        $data_loaninfo_pid['max_overdue_days_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['maxOverdueDays'];
        $data_loaninfo_pid['overdue_tenant_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['overdueTenantCount'];
        $data_loaninfo_pid['overdue_for2_term_tenant_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['overdueFor2TermTenantCount'];
        $data_loaninfo_pid['max_loan_amount_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['maxLoanAmount'];
        $data_loaninfo_pid['average_tenant_gap_days_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['averageTenantGapDays'];
        $data_loaninfo_pid['average_loan_gap_days_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['averageLoanGapDays'];
        $data_loaninfo_pid['loan_tenant_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['loanTenantCount'];
        $data_loaninfo_pid['query_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['queryCount'];
        $data_loaninfo_pid['overdue_loan_count_d90']=$res['loanInfo']['pid']['timeScopes']['D90']['overdueLoanCount'];
        $data_loaninfo_pid['ctime']=$time;
        $data_loaninfo_pid['mobile']=$mobile;
        $res5=$zzc_loaninfo_pid_db->add($data_loaninfo_pid);
        $res5===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_loaninfo_pid表插入失败','ctime'=>time()]):true;

        //中智城--批核&贷后共享数据 --手机号维度
        $data_loaninfo_mobile['max_loan_period_days_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['maxLoanPeriodDays'];
        $data_loaninfo_mobile['average_loan_amount_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['averageLoanAmount'];
        $data_loaninfo_mobile['overdue_for2_term_tenant_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['overdueFor2TermTenantCount'];
        $data_loaninfo_mobile['max_loan_amount_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['maxLoanAmount'];
        $data_loaninfo_mobile['average_tenant_gap_days_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['averageTenantGapDays'];
        $data_loaninfo_mobile['months_from_last_overdue_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['monthsFromLastOverdue'];
        $data_loaninfo_mobile['loan_tenant_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['loanTenantCount'];
        $data_loaninfo_mobile['query_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['queryCount'];
        $data_loaninfo_mobile['overdue_loan_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['overdueLoanCount'];
        $data_loaninfo_mobile['loan_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['loanCount'];
        $data_loaninfo_mobile['remaining_amount_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['remainingAmount'];
        $data_loaninfo_mobile['max_overdue_days_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['maxOverdueDays'];
        $data_loaninfo_mobile['months_from_first_loan_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['monthsFromFirstLoan'];
        $data_loaninfo_mobile['overdue_tenant_count_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['overdueTenantCount'];
        $data_loaninfo_mobile['months_for_normal_repay_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['monthsForNormalRepay'];
        $data_loaninfo_mobile['days_from_last_loan_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['daysFromLastLoan'];
        $data_loaninfo_mobile['average_loan_gap_days_d360']=$res['loanInfo']['mobile']['timeScopes']['D360']['averageLoanGapDays'];
        $data_loaninfo_mobile['max_loan_period_days_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['maxLoanPeriodDays'];
        $data_loaninfo_mobile['average_loan_amount_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['averageLoanAmount'];
        $data_loaninfo_mobile['loan_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['loanCount'];
        $data_loaninfo_mobile['max_overdue_days_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['maxOverdueDays'];
        $data_loaninfo_mobile['overdue_tenant_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['overdueTenantCount'];
        $data_loaninfo_mobile['overdue_for2_term_tenant_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['overdueFor2TermTenantCount'];
        $data_loaninfo_mobile['max_loan_amount_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['maxLoanAmount'];
        $data_loaninfo_mobile['average_tenant_gap_days_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['averageTenantGapDays'];
        $data_loaninfo_mobile['average_loan_gap_days_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['averageLoanGapDays'];
        $data_loaninfo_mobile['loan_tenant_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['loanTenantCount'];
        $data_loaninfo_mobile['query_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['queryCount'];
        $data_loaninfo_mobile['overdue_loan_count_d90']=$res['loanInfo']['mobile']['timeScopes']['D90']['overdueLoanCount'];
        $data_loaninfo_mobile['ctime']=$time;
        $data_loaninfo_mobile['mobile']=$mobile;
        $res6=$zzc_loaninfo_mobile_db->add($data_loaninfo_mobile);
        $res6===false? M('zzc_error_msg','','DB2_ZX')->add(['mobile'=>$mobile,'content'=>'zzc_loaninfo_mobile表插入失败','ctime'=>time()]):true;
    }
    public function test($mobile){
        $user_data = M('user','',C('DB2'))->where(array('id'=>$mobile))->field('username,identity_num,mobile')->find();
//        var_dump($user_data);
        $qh_user_loan_platform_db=M('qh_user_loan_platform','',C('DB2_ZX'));//获取用户所有借贷平台
        $url_3=C('QH_URL').'/MSC8037';
        $qh_user_risk_hint_db=M('qh_user_risk_hint','',C('DB2_ZX'));//获取用户风险提示
        $url_6=C('QH_URL').'/MSC8036';
        $qh_user_risk_db=M('qh_user_risk','',C('DB2_ZX'));//获取用户风险度
        $url_5=C('QH_URL').'/MSC8075';
        $data['name']=$user_data['username'];
        $data['idCard']=$user_data['identity_num'];
        $data['mobile']=$user_data['mobile'];

        $res_3=json_decode(request_post($url_3,$data),true);
//        var_dump($res_3);
        foreach($res_3['data']['records'] as $key=>$value){
            $result=$value;
            $result['mobile']=$user_data['mobile'];
            $result['batchNo']=$res_3['data']['batchNo'];
            $result['ctime'] = time();
            $result_3[]=$result;
        }
        $r=$qh_user_loan_platform_db->addAll($result_3);
        $res_5=json_decode(request_post($url_5,$data),true);
//        var_dump($res_5);
        foreach($res_5['data']['records'] as $key=>$value){
            $result=$value;
            $result['mobile']=$user_data['mobile'];
            $result['batchNo']=$res_5['data']['batchNo'];
            $result['ctime'] = time();
            $result_5[]=$result;
        }
        $r=$qh_user_risk_db->addAll($result_5);
        $res_6=json_decode(request_post($url_6,$data),true);
//        var_dump($res_6);
        foreach($res_6['data']['records'] as $key=>$value){
            $result=$value;
            $result['mobile']=$user_data['mobile'];
            $result['batchNo']=$res_6['data']['batchNo'];
            $result['ctime'] = time();
            $result_6[]=$result;
        }
        $r=$qh_user_risk_hint_db->addAll($result_6);
    }
    function sendRequest($url, $method = 'POST')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if (false !== strpos($url, "https")) {
            // 证书
            // curl_setopt($ch,CURLOPT_CAINFO,"ca.crt");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $resultStr = curl_exec($ch);
        $result = json_decode($resultStr, true);

        return $result;
    }
    /* Generates an available URL */
    function makeURL($method, $action, $region, $secretId, $secretKey, $args)
    {
        /* Add common parameters */
        $args['Nonce'] = (string)rand(0, 0x7fffffff);
        $args['Action'] = $action;
        $args['Region'] = $region;
        $args['SecretId'] = $secretId;
        $args['Timestamp'] = (string)time();

        /* Sort by key (ASCII order, ascending), then calculate signature using HMAC-SHA1 algorithm */
        ksort($args);
        $args['Signature'] = base64_encode(
            hash_hmac(
                'sha1', $method . URL . '?' . $this->makeQueryString($args, false),
                $secretKey, true
            )
        );

        /* Assemble final request URL */

        return 'https://' . URL . '?' . $this->makeQueryString($args, true);
    }
    /* Construct query string from array */
    function makeQueryString($args, $isURLEncoded)
    {
        $arr = array();
        foreach ($args as $key => $value) {
            if (!$isURLEncoded) {
                $arr[] = "$key=$value";
            } else {
                $arr[] = $key . '=' . urlencode($value);
            }
        }
        return implode('&', $arr);
    }
    /* Demo section */
    /* 密钥,请进行替换,密钥申请地址 https://console.qcloud.com/capi  */
//define('SECRET_ID', '');
//define('SECRET_KEY', '');
    function antiFraud($params, $region='gz')
    {
        define('URL', 'csec.api.qcloud.com/v2/index.php');
        define('SECRET_ID', 'AKIDwmZTIAEd7YrvnUsqHXs9ISUKzSmvRtdD');
        define('SECRET_KEY', 'Xt441nOo382nNl160iEZjjXAc4T8lEWf');
        /*
        * 补充用户、行为信息数据,方便我们做更准确的数据模型
        * 协议参考 https://www.qcloud.com/document/product/295/6584
        */
        $url = $this->makeURL('GET', 'AntiFraud', $region, SECRET_ID, SECRET_KEY, $params);
        $result = $this->sendRequest($url);

        return $result;
    }
    public function getcurl($url = '',$data='',$header='')
    {

        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }

    public function anrong(){
        $user_id = I('user_id');
//        $user_id = '1179';
        if(empty($user_id)){
            echo json_encode(['ret'=>'1002','code'=>'缺少用户id']);
            exit();
        }
        $userdata = M('user','',C('DB2'))->where(array('id'=>$user_id))->field('username as truename,identity_num as id_card,mobile')->find();
        $url = 'http://121.43.160.209/Forely/get_ar_xyc?user_id='.$user_id;
        $ress = $this->getcurl($url);
        $result = json_decode($ress, true);
//        var_dump($result);die;
        $this->addanrong($result,$user_id);
        if (!empty($result['applyDetails'])) {
            $res = M('ar_report', '', C('DB2_ZX'))->where(array('user_id' => $user_id))->delete();
            foreach ($result['applyDetails'] as $a => $b) {
                $add = array(
                    'mobile' => $userdata['mobile'],
                    'applydate' => strtotime($result['applyDetails'][$a]['applyDate']),
                    'membertype' => $result['applyDetails'][$a]['memberType'],
                    'creditaddress' => $result['applyDetails'][$a]['creditAddress'],
                    'loantype' => $result['applyDetails'][$a]['loanType'],
                    'loanmoney' => $result['applyDetails'][$a]['loanMoney'],
                    'applyresult' => $result['applyDetails'][$a]['applyResult'],
                    'remark' => $result['applyDetails'][$a]['remark'],
                    'ctime' => time(),
                );
                $addnum[] = $add;
            }
            M('ar_report', '', C('DB2_ZX'))->addALL($addnum);
        }
        echo json_encode(['ret'=>'1001','code'=>'success']);
        exit();
    }
    public function addanrong($data,$user_id){
        $an_risk_db=M('an_risk','',C('DB2_ZX'));
        $an_risk_param_db=M('an_risk_param','',C('DB2_ZX'));
        $res=$data['quickRisk'];
        $risk['user_id']=$user_id;
        $risk['mobile']=$res['baseInfo']['mobile'];
        $risk['mobile_desc']=$res['baseInfo']['mobileDesc'];
        $risk['truename']=$res['baseInfo']['name'];
        $risk['idcard']=$res['baseInfo']['paperNumber'];
        $risk['idcard_desc']=$res['baseInfo']['paperNumberDesc'];
        $risk['query_date']=strtotime($res['baseInfo']['queryDate']);
        $risk['report_number']=$res['baseInfo']['reportNumber'];
        $an_risk_db->add($risk);
        $param['user_id']=$user_id;
        $param['mobile']=$res['baseInfo']['mobile'];
        $param['report_number']=$res['baseInfo']['reportNumber'];
        $param['a001']=$res['riskRule']['A001'];
        $param['a002']=$res['riskRule']['A002'];
        $param['b001']=$res['riskRule']['B001'];
        $param['b002']=$res['riskRule']['B002'];
        $param['b003']=$res['riskRule']['B003'];
        $param['b004']=$res['riskRule']['B004'];
        $param['b005']=$res['riskRule']['B005'];
        $param['c001']=$res['riskRule']['C001'];
        $param['c002']=$res['riskRule']['C002'];
        $param['c003']=$res['riskRule']['C003'];
        $param['d001']=$res['riskRule']['D001'];
        $param['d002']=$res['riskRule']['D002'];
        $param['d003']=$res['riskRule']['D003'];
        $param['d004']=$res['riskRule']['D004'];
        $param['e001']=$res['riskRule']['E001'];
        $param['e002']=$res['riskRule']['E002'];
        $param['e003']=$res['riskRule']['E003'];
        $param['e004']=$res['riskRule']['E004'];
        $param['f001']=$res['riskRule']['F001'];
        $param['f002']=$res['riskRule']['F002'];
        $param['f003']=$res['riskRule']['F003'];
        $param['f004']=$res['riskRule']['F004'];
        $param['g001']=$res['riskRule']['G001'];
        $param['g002']=$res['riskRule']['G002'];
        $param['g003']=$res['riskRule']['G003'];
        $param['g004']=$res['riskRule']['G004'];
        $param['g005']=$res['riskRule']['G005'];
        $param['h001']=$res['riskRule']['H001'];
        $param['h002']=$res['riskRule']['H002'];
        $param['h003']=$res['riskRule']['H003'];
        $param['h004']=$res['riskRule']['H004'];
        $an_risk_param_db->add($param);
    }
}